import {
  _decorator,
  Component,
  instantiate,
  Node,
  Prefab,
  director,
  UITransform,
  Collider2D,
  Contact2DType,
  IPhysics2DContact,
  Label,
  Sprite,
  Button,
  NodeEventType,
  view,
} from "cc";
import { CollisionTag } from "./CollisionTag";
import { BulletControl } from "./BulletControl";
const { ccclass, property } = _decorator;

@ccclass("PlaneControl")
export class PlaneControl extends Component {
  @property({ type: Prefab })
  private bulletPrefab: Prefab = null;

  score = 0;

  @property(Label)
  scoreLabel: Label;

  @property(Node)
  dialog: Node;

  start() {
    this.node.on(Node.EventType.TOUCH_MOVE, this._onTouchMove, this);
    this.schedule(this._genBullet, 0.2);
    const collider2D = this.getComponent(Collider2D);
    if (collider2D) {
      collider2D.on(Contact2DType.BEGIN_CONTACT, this._onBeginContact, this);
    }
  }

  private _onTouchMove(event) {
    const { x, y } = event.getUILocation();
    this.node.setPosition(x, y);
  }

  private _onBeginContact(
    selfCollider: Collider2D,
    otherCollider: Collider2D,
    contact: IPhysics2DContact | null
  ) {
    // 碰到了敌人，游戏结束
    if (otherCollider.tag === CollisionTag.Enemy) {
      // 显示弹窗
      // 如果用 active 的话，director.pause(), 暂停了游戏以后停止了渲染
      // dialog 的事件可能就不响应了
      // this.dialog.active = true;
      // 设置层级
      // this.dialog.setSiblingIndex(this.dialog.parent.children.length - 1);
      // this.dialog.setPosition(
      //   this.dialog.position.x,
      //   view.getDesignResolutionSize().height / 2 + 100
      // );

      director.loadScene("gameover");
    }
  }

  private _genBullet() {
    const bulletPre = instantiate(this.bulletPrefab);
    // 子弹的脚本
    const bulletControl = bulletPre.getComponent(BulletControl);
    bulletControl.killEnemyCallback = () => {
      this.score += 10;
      this.scoreLabel.string = "score：" + this.score;
    };
    this.node.addChild(bulletPre);
    bulletPre.setPosition(
      0,
      this.getComponent(UITransform).contentSize.height / 2 + 5
    );
  }

  update(deltaTime: number) {}
}
